package com.zzxy.spring5.factory;

import com.zzxy.spring5.aspect.MyAspect;
import com.zzxy.spring5.service.IStudentService;
import com.zzxy.spring5.service.impl.StuentServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyBeanFactoryCglib {
    public static IStudentService createStudentService(){
        StuentServiceImpl studentService=new StuentServiceImpl();
        MyAspect aspect =new MyAspect();
         Enhancer enhancer=new Enhancer();
         enhancer.setSuperclass(studentService.getClass());
         enhancer.setCallback(new MethodInterceptor() {
             @Override
             public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                 aspect.before();
                 Object obj=methodProxy.invokeSuper(o,objects);
                 aspect.after();
                 return obj;
             }
         });
         StuentServiceImpl studentserviceProxyCglib= (StuentServiceImpl) enhancer.create();
        return  studentserviceProxyCglib;
    }
}
